package cn.elite.sqlSession;

import cn.elite.config.BoundSql;
import cn.elite.pojo.Configuration;
import cn.elite.pojo.MappedStatement;
import cn.elite.utils.GenericTokenParser;
import cn.elite.utils.ParameterMapping;
import cn.elite.utils.ParameterMappingTokenHandler;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.*;

/**
 * @Author: ZLY
 * @Date: 2020/10/6 16:52
 * @Description:
 */
public class SimpleExecutor implements Executor {
    public Set<String> BASE_TYPE = new HashSet<>();
    {
        BASE_TYPE.add("java.lang.Integer");
        BASE_TYPE.add("java.lang.Char");
        BASE_TYPE.add("java.lang.Boolean");
        BASE_TYPE.add("java.lang.Long");
        BASE_TYPE.add("java.lang.Short");
        BASE_TYPE.add("java.lang.Double");
        BASE_TYPE.add("java.lang.Float");
        BASE_TYPE.add("java.lang.String");
    }


    @Override
    public <T> List<T> query(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
        //1.获取数据库连接
        Connection connection = configuration.getDataSource().getConnection();
        //2.获取sql 语句  select * from user where id=#{id} and username = #{username}
            //解析sql select * from user where id=? and username = ? ,转换过程中,对#{}的值进行存储
        String sql = mappedStatement.getSql();
        BoundSql boundSql= getBoundSql(sql);
        //3.获取预处理对象
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());

        //4.设置参数
        setParamers(mappedStatement, boundSql, preparedStatement, params[0]);
        //5.执行sql
        ResultSet resultSet = preparedStatement.executeQuery();
        Class<?> resultClass = getClassType(mappedStatement.getResultType());
        List<Object> objects = new ArrayList<>();

        //6.封装返回结果集
        while (resultSet.next()){
            Object o = resultClass.newInstance();
            //元数据
            ResultSetMetaData metaData = resultSet.getMetaData();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                //字段名
                String columnName = metaData.getColumnName(i);
                //字段值
                Object object = resultSet.getObject(columnName);

                //使用内省 封装结果集
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultClass);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(o,object);

            }
            objects.add(o);
        }

        return (List<T>) objects;
    }

    private void setParamers(MappedStatement mappedStatement, BoundSql boundSql, PreparedStatement preparedStatement, Object param) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException, SQLException {
        String parameterType = mappedStatement.getParameterType();
        //判断是否基本类型
        if(BASE_TYPE.contains(parameterType)){
            //基本类型直接赋值
            preparedStatement.setObject(1,param);
        }else{
            Class<?> paramClass = getClassType(parameterType);
            List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
            for (int i = 0; i < parameterMappings.size(); i++) {
                ParameterMapping parameterMapping = parameterMappings.get(i);
                //属性值
                String content = parameterMapping.getContent();
                //反射
                Field declaredField = paramClass.getDeclaredField(content);
                //暴力访问
                declaredField.setAccessible(true);
                Object o = declaredField.get(param);
                preparedStatement.setObject(i+1,o);
            }
        }

    }

    @Override
    public int update(Configuration configuration,MappedStatement ms, Object... params) throws Exception {
        //1.获取数据库连接
        Connection connection = configuration.getDataSource().getConnection();
        //2.处理SQL
        String sql = ms.getSql();
        BoundSql boundSql= getBoundSql(sql);
        //3.获取预处理对象
        PreparedStatement ps = connection.prepareStatement(boundSql.getSqlText());
        //4.设置参数
        setParamers(ms, boundSql, ps, params[0]);
        //5 执行SQL
        ps.execute();

        return ps.getUpdateCount();
    }

    private Class<?> getClassType(String parameterType) throws ClassNotFoundException {
        if(parameterType!=null){
            return Class.forName(parameterType);
        }
        return null;
    }

    private BoundSql getBoundSql(String sql) {
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
        String parse = genericTokenParser.parse(sql);
        List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();
        BoundSql boundSql = new BoundSql(parse,parameterMappings);
        return boundSql;
    }

}
